<?php

namespace App\Http\Controllers\Admin\Permission;
use App\Models\Permission;
use App\Http\Controllers\Controller;
use App\Traits\Controllers\AdminTraits;
use App\Traits\Controllers\UpdateStatusTraits;
use App\Transformers\Permission\PermissionTransformer;
use Illuminate\Http\Request;

class PermissionController extends Controller
{
    use AdminTraits;
    use UpdateStatusTraits;

    public $model = Permission::class;
    public $transformer = PermissionTransformer::class;


    /**
     * 参数验证规则
     */
    public function rules(Request $request): array
    {
        switch ($request->method()) {
            case 'GET':
                return [];
                break;
            case 'PATCH':
            case 'PUT':
            case 'POST':
                return [
                    'name' => 'required|min:2|max:100',
                    'cn_name' => 'required|min:2|max:20',
                    'pid' => 'required',
                    'interfacepath' => 'required',
                ];
                break;
        }
        return [

        ];
    }

    public function ruleMessages(): array
    {
        return [
            'name.required' => '权限标识 不能为空',
            'name.min' => '权限标识 必须至少包含2个字段',
            'name.max' => '权限标识 最多包含100个字段',
            'cn_name.required' => '按钮名称 不能为空',
            'cn_name.min' => '按钮名称 最少2个字段',
            'cn_name.max' => '按钮名称 最多20个字段',
            'pid.required' => '父级分类 不能为空',
            'interfacepath.required' => '接口路径 不能为空',
        ];
    }

    /**
     * 列表
     */
    public function index(Request $reques)
    {
        $data = $this->getQuery()->with('children.children')->get();

        return $data;
    }

    /**
     *添加
     */
    public function store(Request $request)
    {
        $this->validateData($request);

        //通过模型拿到等级 通过条件拿到id和pid 拿到等级的值
        $level = $this->getQuery()->select('level')
            ->where('id', $request->pid)->value('level');

        if ($level >= 4) {
            return $this->response->errorBadRequest('最大等级不能超过4级');
        }
        //等级1
        $request->offsetSet('level', $level + 1);
        // 保存创建人
        $request->offsetSet('system_admin_id', $this->admin_user('id'));
        $model = $this->getQuery()->fill($request->all());

        $model->save();

        return $this->response->created();
    }

    /**
     * 删除
     */
    public function destroy($id, Request $request)
    {
        $data = $this->getQuery()->where('pid', $id)->get()->count();

        if ($data > 0) {

            return $this->response->errorBadRequest('请先删除菜单下面的子菜单');

        } else {
            $this->getQuery()->where('id', $id)->delete();
        }
        return $this->response->created();
    }
}














